import Vue from 'vue'
import Router from 'vue-router'
import Layout from './layout'
import Index from './views/index'

import store from './store'

Vue.use(Router)

const files = require.context('./routes', true, /\.js$/)
let routes = []
files.keys().forEach((file) => {
  routes.push(...files(file).default)
})

const createRouter = () => {
  const router = new Router({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [
      {
        path: '/',
        component: Layout,
        meta: {
          title: '首页'
        },
        children: [
          {
            path: '',
            name: 'index',
            meta: {
              title: '首页'
            },
            component: Index
          },
          {
            path: 'editpwd',
            name: 'Editpwd',
            meta: {
              title: '修改密码'
            },
            component: () => import('./views/editpwd')
          },
          {
            path: 'noauth',
            name: 'noauth',
            meta: {
              title: '权限不足'
            },
            component: () => import('./views/noauth')
          },
          {
            path: 'export',
            name: 'export',
            meta: {
              title: '导出记录'
            },
            component: () => import('./views/export')
          },
        ]
      },
      ...routes,
      {
        path: '/login',
        name: 'login',
        meta: {
          title: '登陆入口'
        },
        component: () =>import('./views/login')
      },
      {
        path: '*',
        name: '404',
        component: () =>import('./views/common/404')
      }
    ]
  })

  router.beforeEach((to, from, next) => {
    document.title = '后台管理 - ' + to.meta.title
    store.commit('router/set', to)
    if (to.name !== 'login' && !store.getters['auth/isLogin']) {
      return next({
        name: 'login'
      })
    }
    // 权限校验
    let rules = store.getters['auth/rules']
    if (to.name !== 'noauth' && rules && rules.length
      && !rules.includes('All')
      && to.meta?.auth && !rules.includes(to.meta?.auth)) {
      console.log('没有权限')
      return next({
        name: 'noauth'
      })
    }
    next()
  })
  return router
}

export default createRouter()

export { routes, createRouter }
